/** @format */

const { CURD_REQUEST } = require('./request')

class BaseDao {
  constructor(context, dbName) {
    this.consumeId = context.consumeId
    this.TABLE = dbName
  }
  /**
   * 查询一条数据
   * @param query
   * @param options
   */
  async findOne(query, options) {
    let result = await CURD_REQUEST({
      consumeId: this.consumeId,
      TABLE: this.TABLE,
      type: `find`,
      query: query || {},
      options: options || {}
    })
    return result[0]
  }
  /**
   * 查询多条数据
   * @param query
   * @param options
   */
  async find(query, options) {
    console.log(`consumeId`, this.consumeId)
    let result = await CURD_REQUEST({
      consumeId: this.consumeId,
      TABLE: this.TABLE,
      type: `find`,
      query: query || {},
      options: options || {}
    })
    return result
  }

  /**
   * 插入单条数据
   * @param document
   */
  async insertOne(document) {
    console.log(`insertOne`, document)
    let result = await CURD_REQUEST({ consumeId: this.consumeId, TABLE: this.TABLE, type: `insert`, document: document || {} })
    return result._id || result.inertId || result
  }

  /**
   * 插入多条数据
   * @param documents 插入对象
   */
  async insertMany(documents) {
    let result = await CURD_REQUEST({ consumeId: this.consumeId, TABLE: this.TABLE, type: `insert`, document: documents || [{}] })
    return result
  }

  /**
   * 更新数据
   * @param query
   * @param options
   */
  async update(query, options) {
    let result = await CURD_REQUEST({
      consumeId: this.consumeId,
      TABLE: this.TABLE,
      type: `update`,
      query: query || {},
      options: options || {}
    })
    console.log(result)
    let res = result && result.nModified > 0 ? 1 : 0
    console.log(`update结果`, res)
    return res
  }

  /**
   * 删除多条数据
   * @param query
   * @param options
   */
  async delete(query, options) {
    let result = await CURD_REQUEST({
      consumeId: this.consumeId,
      TABLE: this.TABLE,
      type: `delete`,
      query: query || {},
      options: options || {}
    })
    return result
  }

  /**
   * 获取条目数
   * @param query
   * @param options
   */
  async count(query, options) {
    let result = await CURD_REQUEST({
      consumeId: this.consumeId,
      TABLE: this.TABLE,
      type: `count`,
      query: query || {},
      options: options || {}
    })
    return result
  }

  /**
   * 聚合查询
   * @param query
   * @param options
   */
  async aggregate(query) {
    let result = await CURD_REQUEST({
      consumeId: this.consumeId,
      TABLE: this.TABLE,
      type: `aggregate`,
      query: query || {}
    })
    return result
  }
}

module.exports = BaseDao
